import {  geneRouters } from '@/router'
import {  getItem, removeItem } from '@/utils/save'

function roleHasPermisson(route, role) {
  if (!route) {
    return false
  }

  if (!route.meta || route.const_page) {
    return true
  }

  if (!route.meta.roles) {
    return false
  }

  return role.every(ro => {
    if (route.meta.roles.indexOf(ro) > 0) {
      return true
    }
    return false
  })
}

function filterUserRouter(routers, role) {
  const aroutes = routers.filter(route => {
    if (roleHasPermisson(route, role)) {
      if (route.children && route.children.length > 0) {
        route.children = filterUserRouter(route.children, role)
      }
      return true
    }
    return false
  })
  return aroutes
}

const routes = {
  state: {
    routers: geneRouters,
  },
  getters:{
    getRoutes(state) {
      const uinfo = getItem('user_info')
      state.routers = filterUserRouter(geneRouters, uinfo.roles)
      return state.routers
    }
  },
  mutations: {
    setRouters: (state, routers) => {
      state.routers = routers
    }
  },
  actions: {
    async resetRoutes({ commit, state }, { roles }) {
      console.log("--resetRoutes", this.$router)
      commit('setRouters', filterUserRouter(geneRouters, roles))
    }
  }
}

export default routes